import { ipcRenderer, remote } from 'electron';
import Noun from './Noun.js'
const { Menu, MenuItem, dialog } = remote;
import RD from './qbasics/basics/Phere.js'
import fs from "fs";

let currentFile = null; //当前文档保存的路径
let isSaved = true;     //当前文档是否已保存
let txtEditor = document.getElementById('txtEditor'); //获得TextArea文本框的引用
let phere= new RD();
let saveStr = document.getElementById('saveStr');
let showStr = document.getElementById('showStr');

let editStr = document.getElementById('editStr');

let delStr = document.getElementById('delStr');
document.title = "Notepad - Untitled"; //设置文档标题，影响窗口标题栏名称
let par =  document.getElementById('container')
//给文本框增加右键菜单
const contextMenuTemplate=[
    { role: 'undo' },       //Undo菜单项
    { role: 'redo' },       //Redo菜单项
    { type: 'separator' },  //分隔线
    { role: 'cut' },        //Cut菜单项
    { role: 'copy' },       //Copy菜单项
    { role: 'paste' },      //Paste菜单项
    { role: 'delete' },     //Delete菜单项
    { type: 'separator' },  //分隔线
    { role: 'selectall' }   //Select All菜单项
];
const contextMenu=Menu.buildFromTemplate(contextMenuTemplate);
txtEditor.addEventListener('contextmenu', (e)=>{
    e.preventDefault();
    contextMenu.popup(remote.getCurrentWindow());
});

//监控文本框内容是否改变
txtEditor.oninput=(e)=>{
    if(isSaved) document.title += " *";
    isSaved=false;
};

//监听与主进程的通信
ipcRenderer.on('action', (event, arg) => {
    switch(arg){
    case 'new': //新建文件
        askSaveIfNeed();
        currentFile=null;
        txtEditor.value='';
        document.title = "Notepad - Untitled";
        //remote.getCurrentWindow().setTitle("Notepad - Untitled *");
          phere= new RD();
        let toTrees = phere.toTreeNum(1);
        par.innerHTML="";
        generate([toTrees],par) ;

        isSaved=true;
        break;
    case 'open': //打开文件
        askSaveIfNeed();
        const files = remote.dialog.showOpenDialog(remote.getCurrentWindow(), {
            filters: [
                { name: "rd Files", extensions: ['rd'] },
                { name: "Text Files", extensions: ['txt', 'js', 'html', 'md','config','jsr'] },
                { name: 'All Files', extensions: ['*'] } ],
            properties: ['openFile']
        });
        files.then(file=>{
            currentFile=file.filePaths[0];
            const json=readText(currentFile);
            par.innerHTML="";
            generate([json],par) ;
            document.title = "Notepad - " + currentFile;
            isSaved=true;
        })
        break;
    case 'save': //保存文件
        saveCurrentDoc();
        break;
     case 'compile': //保存文件
         compileCurrentDoc();
            break;
    case 'exiting':
        askSaveIfNeed();
        ipcRenderer.sendSync('reqaction', 'exit');
        break;
    }
});

//读取文本文件
function readText(file){
    const fs = require('fs');
    debugger
    let data=fs.readFileSync(file);
      phere =new RD();
    phere.loadData(data);
    let toTree = phere.toTreeNum(1);
    return toTree ;
}

//删除
delStr.onclick =(e)=>{
    let id = document.getElementById('id').value;
    phere.delId(id);

    let toTree = phere.toTreeNum(1);
    par.innerHTML="";
    generate([toTree],par) ;
    return  ;
}
//保存
saveStr.onclick =(e)=>{
    let id = document.getElementById('id').value;
    let pid = document.getElementById('pid').value;
    let name = document.getElementById('name').value;
    let value = document.getElementById('value').value;
    let type = document.getElementById('type').value;
    // phere.addRow()
    phere.saveRow(id,pid,name,value,type)
    let toTree = phere.toTreeNum(1);
    par.innerHTML="";
    generate([toTree],par) ;
    return  ;
}
//编辑
showStr.onclick =(e)=>{
    let toTree = phere.toTree(1);

    par.innerHTML="";
    generate([toTree],par) ;
    return  ;
}
//查看
editStr.onclick =(e)=>{
    let toTree = phere.toTreeNum(1);
    par.innerHTML="";
    generate([toTree],par) ;
    return  ;
}


function generate(json,pars)
{
    for(var attr in json)
    {
        var ele=document.createElement('li');
        ele.id= "li" + json[attr].id
        ele.key= json[attr].id
        if(!json[attr].children)
            ele.innerHTML=' <input type="checkbox"></input>'+` 
                    <span       > 
                                ${json[attr].id} 
                                 <button type="button" onclick="toStr(    '${json[attr].id}' ,'${ json[attr].pid}' ,  '${json[attr]. name}' , '${json[attr].value}' , '${json[attr].type}' )" >选中 </button> 
        
                                ${ json[attr].pid} ,  ${json[attr]. name} , ${json[attr].value} , ${json[attr].type} 
                        </span>`;
        else
        {
            ele.innerHTML=`<span><span class="switch-open" onclick="toggle(this)"></span><input type="checkbox" onclick="checkChange(this)"></input>  
                         
                       <span       > 
                                ${json[attr].id} 
                                                              <button type="button" onclick="toStr(    '${json[attr].id}' ,'${ json[attr].pid}' ,  '${json[attr]. name}' , '${json[attr].value}' , '${json[attr].type}' )" >选中 </button> 
                                  ${ json[attr].pid} ,  ${json[attr]. name} , ${json[attr].value} , ${json[attr].type} 

                        </span>
                    </span>`;
            var nextpar=document.createElement('ul');
            ele.appendChild(nextpar);
            generate(json[attr].children,nextpar);
        }
        pars.appendChild(ele);
    }
}
//保存文本内容到文件
function saveText(pheres, file){
    const fs = require('fs');
    let uint8Array = pheres.outData();
    fs.writeFileSync(file, new Uint8Array(uint8Array));
}



//保存当前文档
function saveCurrentDoc(){
    if(!currentFile){
        const file = remote.dialog.showSaveDialog(remote.getCurrentWindow(), {
            filters: [
                { name: 'rd', extensions: ['rd'] },
                { name: "Text Files", extensions: ['txt', 'js', 'html', 'md','config','rd'] },

                { name: 'All Files', extensions: ['*'] } ]
        });
        if(file) {
            file.then(
                nResolved => {
                    currentFile=nResolved.filePath;
                    saveText(phere, currentFile);
                    isSaved=true;
                    document.title = "Notepad - " + currentFile;
                },
                onRejected => {console.log('Promise rejected')}
            )

        }
    }
    if(currentFile){

        saveText(phere, currentFile);
        isSaved=true;
        document.title = "Notepad - " + currentFile;
    }
}

//如果需要保存，弹出保存对话框询问用户是否保存当前文档
function askSaveIfNeed(){
    if(isSaved) return;
    const response=dialog.showMessageBox(remote.getCurrentWindow(), {
        message: 'Do you want to save the current document?',
        type: 'question',
        buttons: [ 'Yes', 'No' ]
    });
    if(response==0) saveCurrentDoc(); //点击Yes按钮后保存当前文档
}


function  compileCurrentDoc() {
    const txtSave=txtEditor.value;
    let noun =new Noun();
    let res= noun.utfToFour(txtSave);
    res=res.replace(/a/g,'a ');
    res=res.replace(/b/g,'b\n');
    res=res.replace(/c/g,'c\n\n');
    txtEditor1.value=res;
}
